package com.jcli.HslCommunication.HslCommunicationDemo;

import com.jcli.HslCommunication.BasicFramework.SoftBasic;
import com.jcli.HslCommunication.Core.Types.OperateResult;
import com.jcli.HslCommunication.Core.Types.OperateResultExOne;
import com.jcli.HslCommunication.Profinet.Melsec.MelsecA1ENet;
import com.jcli.HslCommunication.Profinet.SiemensS7Net.SiemensS7Net;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.text.SimpleDateFormat;
import java.util.Date;

public class FormMelsecA1E extends JDialog {

    // 创建MelsecA1ENet实例用于PLC通信
    private MelsecA1ENet melsecMcNet = null;  // 用于与三菱PLC通信的MelsecA1ENet实例
    private JPanel panelContent = null;        // 窗体的内容面板
    private String defaultAddress = "D100";    // 默认的PLC地址

    private static SimpleDateFormat dateFormat = new SimpleDateFormat("[HH:mm:ss] ");

    private JTextArea textArea;
    private int readCount; // 读取计数器
    private boolean isReading; // 用于标识是否正在读取

    // 构造函数
    public FormMelsecA1E() {
        // 设置窗体标题、大小、位置等属性
        this.setTitle("三菱PLC验证");
        this.setSize(1020, 684);
        this.setLocationRelativeTo(null); // 将窗体放置在屏幕中央
        this.setModal(true);  // 创建模态对话框

        JPanel panel = new JPanel();
        panel.setLayout(null);  // 使用空布局管理器

        // 向面板中添加一些标签和信息
        AddNormal(panel);

        // 向面板中添加与连接相关的UI元素
        AddConnectSegment(panel);

        // 向面板中添加内容区域
        AddContent(panel);

        this.add(panel);  // 将面板添加到窗体中

        // 初始化MelsecA1ENet实例，用于与PLC通信
        melsecMcNet = new MelsecA1ENet();
    }

    // 添加一些普通的标签和信息，文字描述
    public void AddNormal(JPanel panel) {
        // 添加博客信息标签
        JLabel label1 = new JLabel("Blogs：");  // 创建标签，显示 "Blogs："
        label1.setBounds(11, 9, 68, 17);  // 设置标签的位置和大小
        panel.add(label1);  // 将标签添加到面板中

        JLabel label5 = new JLabel("标签");  // 创建标签，显示博客链接
        label5.setBounds(80, 9, 400, 17);  // 设置标签的位置和大小
        panel.add(label5);  // 将标签添加到面板中

        // 添加协议信息标签
        JLabel label2 = new JLabel("协议：");  // 创建标签，显示 "协议"
        label2.setBounds(466, 9, 68, 17);  // 设置标签的位置和大小
        panel.add(label2);  // 将标签添加到面板中

        JLabel label3 = new JLabel("Qna-3E A1E");  // 创建标签，显示协议信息
        label3.setForeground(new Color(255, 0, 0));  // 设置标签文字颜色为红色
        label3.setBounds(540, 9, 160, 17);  // 设置标签的位置和大小
        panel.add(label3);  // 将标签添加到面板中

        // 添加作者信息标签
        JLabel label4 = new JLabel("By jcli");  // 创建标签，显示作者信息
        label4.setForeground(Color.ORANGE);  // 设置标签文字颜色为橙色
        label4.setBounds(887, 9, 108, 17);  // 设置标签的位置和大小
        panel.add(label4);  // 将标签添加到面板中
    }

    // 添加连接相关的UI元素
    public void AddConnectSegment(JPanel panel) {
        // 创建连接相关的面板
        JPanel panelConnect = new JPanel();  // 创建一个新的面板用于承载连接相关的UI元素
        panelConnect.setLayout(null);  // 设置面板的布局管理器为null，以允许手动设置元素位置
        panelConnect.setBounds(14, 32, 978, 54);  // 设置面板的位置和大小，左上角坐标 (14, 32)，宽度 978，高度 54
        panelConnect.setBorder(BorderFactory.createTitledBorder(""));  // 设置面板的边框，这里创建一个没有标题的边框

        // 添加IP地址标签和文本框
        JLabel label1 = new JLabel("Ip：");  // 创建标签，显示 "Ip："
        label1.setBounds(8, 17, 56, 17);  // 设置标签的位置和大小
        panelConnect.add(label1);

        JTextField textField1 = new JTextField();  // 创建文本框用于输入IP地址
        textField1.setBounds(62, 14, 106, 23);  // 设置文本框的位置和大小
        textField1.setText("192.168.1.11");  // 设置默认的IP地址
        panelConnect.add(textField1);

        // 添加端口标签和文本框
        JLabel label2 = new JLabel("Port：");  // 创建标签，显示 "Port："
        label2.setBounds(184, 17, 56, 17);  // 设置标签的位置和大小
        panelConnect.add(label2);

        JTextField textField2 = new JTextField();  // 创建文本框用于输入端口号
        textField2.setBounds(238, 14, 61, 23);  // 设置文本框的位置和大小
        textField2.setText("3000");  // 设置默认的端口号
        panelConnect.add(textField2);

        // 添加连接和断开连接按钮
        JButton button2 = new JButton("Disconnect");  // 创建断开连接按钮
        button2.setFocusPainted(false);  // 设置按钮无焦点边框
        button2.setBounds(584, 11, 121, 28);  // 设置按钮的位置和大小
        panelConnect.add(button2);

        JButton button1 = new JButton("Connect");  // 创建连接按钮
        button1.setFocusPainted(false);  // 设置按钮无焦点边框
        button1.setBounds(477, 11, 91, 28);  // 设置按钮的位置和大小
        panelConnect.add(button1);

        button2.setEnabled(false);  // 初始化时禁用断开连接按钮
        button1.setEnabled(true);   // 初始化时启用连接按钮

        // 监听连接按钮的点击事件
        button1.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                // 检查按钮是否被禁用，如果被禁用则不执行后续操作
                if (button1.isEnabled() == false) return;
                super.mouseClicked(e);  // 调用父类的 mouseClicked 方法

                try {
                    // 通过 textField1 和 textField2 获取用户输入的 IP 地址和端口号
                    melsecMcNet.setIpAddress(textField1.getText()); // 从 textField1 获取用户输入的IP地址
                    melsecMcNet.setPort(Integer.parseInt(textField2.getText())); // 从 textField2 获取用户输入的端口号

                    // 连接到 PLC 设备
                    OperateResult connect = melsecMcNet.ConnectServer(); // 调用连接服务器的方法
                    // 初始化计数器和读取状态
                    readCount = 0;
                    isReading = false;
                    if (connect.IsSuccess) { // 如果连接成功
                        // 连接成功时，显示成功消息框
                        JOptionPane.showMessageDialog(
                                null,
                                "Connect Success", // 消息框的消息内容
                                "Result", // 消息框标题
                                JOptionPane.PLAIN_MESSAGE); // 消息框类型为普通消息

                        // 启用内容区域的 UI 元素，通常是在连接成功后才允许用户进行其他操作
                        DemoUtils.SetPanelEnabled(panelContent, true); // 启用内容区域的UI元素
                        button2.setEnabled(true);  // 启用断开连接按钮
                        button1.setEnabled(false); // 禁用当前连接按钮，避免重复连接
                    } else {
                        // 连接失败时，显示失败消息框
                        JOptionPane.showMessageDialog(
                                null,
                                "Connect Failed:" + connect.ToMessageShowString(), // 显示失败原因
                                "Result", // 消息框标题
                                JOptionPane.WARNING_MESSAGE); // 消息框类型为警告消息
                    }
                } catch (Exception ex) {
                    // 异常处理，当连接过程中出现异常时，显示错误消息框
                    JOptionPane.showMessageDialog(
                            null,
                            "Connect Failed\r\nReason:" + ex.getMessage(), // 显示错误原因
                            "Result", // 消息框标题
                            JOptionPane.ERROR_MESSAGE); // 消息框类型为错误消息
                }

            }
        });

        // 监听断开连接按钮的点击事件
        button2.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                super.mouseClicked(e);
                if (button2.isEnabled() == false) return; // 如果断开按钮被禁用，不执行后续操作

                if (melsecMcNet != null) { // 检查是否存在有效的 MelsecMcNet 对象
                    // 断开连接
                    melsecMcNet.ConnectClose(); // 调用断开连接的方法
                    button1.setEnabled(true);  // 启用连接按钮，允许重新连接
                    button2.setEnabled(false); // 禁用断开连接按钮，避免重复断开

                    // 禁用内容区域的 UI 元素，通常在断开连接后不允许用户进行其他操作
                    DemoUtils.SetPanelEnabled(panelContent, false); // 禁用内容区域的UI元素
                }
            }
        });


        panel.add(panelConnect);  // 将连接相关的面板添加到主面板
    }

    // 添加内容区域·下方
    public void AddContent(JPanel panel) {
        // 创建一个名为 panelContent 的 JPanel，用于容纳内容区域的UI元素
        JPanel panelContent = new JPanel();

        // 使用手动布局管理器（null布局）
        panelContent.setLayout(null);

        // 设置 panelContent 的位置和大小
        panelContent.setBounds(14, 95, 978, 537);

        // 设置 panelContent 的边框为空，即没有可见的边框
        panelContent.setBorder(BorderFactory.createTitledBorder(""));

        // 向 panelContent 中添加各种UI元素

        // 添加读取单个数据的UI元素
        AddRead(panelContent);

        // 添加写入单个数据的UI元素
        AddWrite(panelContent);

        // 添加按长度逐个字节读取的UI元素
        AddReadBulk(panelContent);

        AddReadAll(panelContent);

        // 添加报文读取测试的UI元素
        AddCoreRead(panelContent);

        // 将 panelContent 添加到传入的 panel（通常是 FormMelsecA1E 的主面板）
        panel.add(panelContent);

        // 将当前 panelContent 的引用存储在 FormMelsecA1E 类的成员变量 this.panelContent 中
        this.panelContent = panelContent;

        // 在初始化时禁用内容区域的UI元素
        DemoUtils.SetPanelEnabled(this.panelContent, false);
    }

    // 添加读取单个数据的UI元素
    public void AddRead(JPanel panel) {
        JPanel panelRead = new JPanel();
        panelRead.setLayout(null);
        panelRead.setBounds(11, 3, 518, 234);
        panelRead.setBorder(BorderFactory.createTitledBorder("Read Single Test"));

        // 添加地址标签和文本框
        JLabel label1 = new JLabel("Address：");
        label1.setBounds(9, 30, 70, 17);
        panelRead.add(label1);

        JTextField textField1 = new JTextField();
        textField1.setBounds(83, 27, 213, 23);
        textField1.setText(defaultAddress);
        panelRead.add(textField1);

        // 添加结果标签和文本框
        JLabel label2 = new JLabel("Result：");
        label2.setBounds(9, 58, 70, 17);
        panelRead.add(label2);

        JTextArea textArea1 = new JTextArea();
        textArea1.setLineWrap(true);
        JScrollPane jsp = new JScrollPane(textArea1);
        jsp.setBounds(83, 56, 213, 164);
        panelRead.add(jsp);

        // 添加读取按钮（不同数据类型）
        JButton button1 = new JButton("r-bit");
        button1.setFocusPainted(false);
        button1.setBounds(315, 19, 82, 28);
        button1.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if (button1.isEnabled() == false) return;
                super.mouseClicked(e);
                // 读取位数据   使用 DemoUtils.ReadResultRender 方法读取布尔值并在界面上显示结果
                DemoUtils.ReadResultRender(melsecMcNet.ReadBool(textField1.getText()), textField1.getText(), textArea1, jsp);
            }
        });
        panelRead.add(button1);

        // 添加其他读取按钮，例如r-short、r-int、r-float等
        JButton button3 = new JButton("r-short");
        button3.setFocusPainted(false);
        button3.setBounds(315, 56, 82, 28);
        button3.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if (button3.isEnabled() == false) return;
                super.mouseClicked(e);
                DemoUtils.ReadResultRender(melsecMcNet.ReadInt16(textField1.getText()), textField1.getText(), textArea1, jsp);
            }
        });
        panelRead.add(button3);

        JButton button4 = new JButton("r-ushort");
        button4.setFocusPainted(false);
        button4.setVisible(false);
        button4.setBounds(415, 56, 82, 28);
        panelRead.add(button4);

        JButton button5 = new JButton("r-int");
        button5.setFocusPainted(false);
        button5.setBounds(315, 90, 82, 28);
        button5.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if (button5.isEnabled() == false) return;
                super.mouseClicked(e);
                DemoUtils.ReadResultRender(melsecMcNet.ReadInt32(textField1.getText()), textField1.getText(), textArea1, jsp);
            }
        });
        panelRead.add(button5);

        JButton button6 = new JButton("r-uint");
        button6.setFocusPainted(false);
        button6.setVisible(false);
        button6.setBounds(415, 90, 82, 28);
        panelRead.add(button6);

        JButton button7 = new JButton("r-long");
        button7.setFocusPainted(false);
        button7.setBounds(315, 124, 82, 28);
        button7.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if (button7.isEnabled() == false) return;
                super.mouseClicked(e);
                DemoUtils.ReadResultRender(melsecMcNet.ReadInt64(textField1.getText()), textField1.getText(), textArea1, jsp);
            }
        });
        panelRead.add(button7);

        JButton button8 = new JButton("r-ulong");
        button8.setFocusPainted(false);
        button8.setVisible(false);
        button8.setBounds(415, 124, 82, 28);
        panelRead.add(button8);

        JButton button9 = new JButton("r-float"); // 创建名为 button9 的按钮，用于读取浮点数数据
        button9.setFocusPainted(false); // 设置按钮不绘制焦点矩形框
        button9.setBounds(315, 158, 82, 28); // 设置按钮的位置和大小

        // 为按钮添加鼠标点击事件的监听器
        button9.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if (button9.isEnabled() == false) return; // 如果按钮被禁用，则不执行后续操作
                super.mouseClicked(e); // 调用父类的 mouseClicked 方法

                // 使用 melsecMcNet.ReadFloat 方法读取浮点数数据，并将结果显示在界面上
                DemoUtils.ReadResultRender(melsecMcNet.ReadFloat(textField1.getText()), textField1.getText(), textArea1, jsp);
            }
        });

        panelRead.add(button9); // 将按钮添加到名为 panelRead 的面板中


        JButton button10 = new JButton("r-double");
        button10.setFocusPainted(false);
        button10.setBounds(415, 158, 82, 28);
        button10.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if (button10.isEnabled() == false) return;
                super.mouseClicked(e);
                DemoUtils.ReadResultRender(melsecMcNet.ReadDouble(textField1.getText()), textField1.getText(), textArea1, jsp);
            }
        });
        panelRead.add(button10);

        // 添加 "Length" 标签和文本框
        JLabel label8 = new JLabel("Length:");
        label8.setBounds(315, 198, 55, 17);
        panelRead.add(label8);

        JTextField textField8 = new JTextField();
        textField8.setBounds(358, 195, 41, 23);
        textField8.setText("10");
        panelRead.add(textField8);

        // 添加读取字符串的按钮
        JButton button11 = new JButton("r-string");
        button11.setFocusPainted(false);
        button11.setBounds(415, 192, 82, 28);
        button11.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if (button11.isEnabled() == false) return;
                super.mouseClicked(e);
                // 使用 DemoUtils.ReadResultRender 方法读取字符串并在界面上显示结果
                DemoUtils.ReadResultRender(melsecMcNet.ReadString(textField1.getText(), Short.parseShort(textField8.getText())), textField1.getText(), textArea1, jsp);
            }
        });
        panelRead.add(button11);

        // 将 panelRead 添加到传入的 panel（通常是 FormMelsecA1E 的主面板）
        panel.add(panelRead);
    }

    // 添加写入单个数据的UI元素
    public void AddWrite(JPanel panel) {
        JPanel panelWrite = new JPanel();
        panelWrite.setLayout(null);
        panelWrite.setBounds(546, 3, 419, 234);
        panelWrite.setBorder(BorderFactory.createTitledBorder("Write Single Test"));

        // 添加地址标签和文本框
        JLabel label1 = new JLabel("Address：");
        label1.setBounds(9, 30, 70, 17);
        panelWrite.add(label1);

        JTextField textField1 = new JTextField();
        textField1.setBounds(83, 27, 132, 23);
        textField1.setText(defaultAddress);
        panelWrite.add(textField1);

        // 添加值标签和文本框
        JLabel label2 = new JLabel("Value：");
        label2.setBounds(9, 58, 70, 17);
        panelWrite.add(label2);

        JTextField textField2 = new JTextField();
        textField2.setBounds(83, 56, 132, 23);
        panelWrite.add(textField2);

        // 添加注意事项标签
        JLabel label100 = new JLabel("Note: The value of \r\nthe string needs to be converted");
        label100.setBounds(61, 82, 147, 58);
        panelWrite.add(label100);

        // 添加写入按钮（不同数据类型）
        JButton button1 = new JButton("w-bit");
        button1.setFocusPainted(false);
        button1.setBounds(226, 24, 82, 28);
        button1.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if (button1.isEnabled() == false) return;
                super.mouseClicked(e);
                try {
                    // 写入位数据
                    DemoUtils.WriteResultRender(melsecMcNet.Write(textField1.getText(), Boolean.parseBoolean(textField2.getText())), textField1.getText());
                } catch (Exception ex) {
                    JOptionPane.showMessageDialog(
                            null,
                            "Write Failed:" + ex.getMessage(),
                            "Result",
                            JOptionPane.ERROR_MESSAGE);
                }
            }
        });
        panelWrite.add(button1);

        // 添加其他写入按钮，例如w-short、w-int、w-float等
        JButton button3 = new JButton("w-short");
        button3.setFocusPainted(false);
        button3.setBounds(226, 61, 82, 28);
        button3.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if (button3.isEnabled() == false) return;
                super.mouseClicked(e);
                try {
                    DemoUtils.WriteResultRender(melsecMcNet.Write(textField1.getText(), Short.parseShort(textField2.getText())), textField1.getText());
                } catch (Exception ex) {
                    JOptionPane.showMessageDialog(
                            null,
                            "Write Failed:" + ex.getMessage(),
                            "Result",
                            JOptionPane.ERROR_MESSAGE);
                }
            }
        });
        panelWrite.add(button3);

        JButton button4 = new JButton("w-ushort");
        button4.setFocusPainted(false);
        button4.setVisible(false);
        button4.setBounds(326, 61, 82, 28);
        panelWrite.add(button4);

        JButton button5 = new JButton("w-int");
        button5.setFocusPainted(false);
        button5.setBounds(226, 95, 82, 28);
        button5.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if (button5.isEnabled() == false) return;
                super.mouseClicked(e);
                try {
                    DemoUtils.WriteResultRender(melsecMcNet.Write(textField1.getText(), Integer.parseInt(textField2.getText())), textField1.getText());
                } catch (Exception ex) {
                    JOptionPane.showMessageDialog(
                            null,
                            "Write Failed:" + ex.getMessage(),
                            "Result",
                            JOptionPane.ERROR_MESSAGE);
                }
            }
        });
        panelWrite.add(button5);

        JButton button6 = new JButton("w-uint");
        button6.setFocusPainted(false);
        button6.setVisible(false);
        button6.setBounds(326, 95, 82, 28);
        panelWrite.add(button6);

        JButton button7 = new JButton("w-long");
        button7.setFocusPainted(false);
        button7.setBounds(226, 129, 82, 28);
        button7.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if (button7.isEnabled() == false) return;
                super.mouseClicked(e);
                try {
                    DemoUtils.WriteResultRender(melsecMcNet.Write(textField1.getText(), Long.parseLong(textField2.getText())), textField1.getText());
                } catch (Exception ex) {
                    JOptionPane.showMessageDialog(
                            null,
                            "Write Failed:" + ex.getMessage(),
                            "Result",
                            JOptionPane.ERROR_MESSAGE);
                }
            }
        });
        panelWrite.add(button7);

        JButton button8 = new JButton("w-ulong");
        button8.setFocusPainted(false);
        button8.setVisible(false);
        button8.setBounds(326, 129, 82, 28);
        panelWrite.add(button8);

        JButton button9 = new JButton("w-float");
        button9.setFocusPainted(false);
        button9.setBounds(226, 163, 82, 28);
        button9.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if (button9.isEnabled() == false) return;
                super.mouseClicked(e);
                try {
                    DemoUtils.WriteResultRender(melsecMcNet.Write(textField1.getText(), Float.parseFloat(textField2.getText())), textField1.getText());
                } catch (Exception ex) {
                    JOptionPane.showMessageDialog(
                            null,
                            "Write Failed:" + ex.getMessage(),
                            "Result",
                            JOptionPane.ERROR_MESSAGE);
                }
            }
        });
        panelWrite.add(button9);

        JButton button10 = new JButton("w-double");
        button10.setMargin(new Insets(0, 0, 0, 0));
        button10.setFocusPainted(false);
        button10.setBounds(326, 163, 82, 28);
        button10.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if (button10.isEnabled() == false) return;
                super.mouseClicked(e);
                try {
                    DemoUtils.WriteResultRender(melsecMcNet.Write(textField1.getText(), Double.parseDouble(textField2.getText())), textField1.getText());
                } catch (Exception ex) {
                    JOptionPane.showMessageDialog(
                            null,
                            "Write Failed:" + ex.getMessage(),
                            "Result",
                            JOptionPane.ERROR_MESSAGE);
                }
            }
        });
        panelWrite.add(button10);

        JButton button11 = new JButton("w-string");
        button11.setFocusPainted(false);
        button11.setBounds(326, 197, 82, 28);
        button11.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if (button11.isEnabled() == false) return;
                super.mouseClicked(e);
                try {
                    DemoUtils.WriteResultRender(melsecMcNet.Write(textField1.getText(), textField2.getText()), textField1.getText());
                } catch (Exception ex) {
                    JOptionPane.showMessageDialog(
                            null,
                            "Write Failed:" + ex.getMessage(),
                            "Result",
                            JOptionPane.ERROR_MESSAGE);
                }
            }
        });
        panelWrite.add(button11);

        panel.add(panelWrite);
    }


    // 添加按长度逐个字节读取的UI元素
    public void AddReadBulk(JPanel panel) {
        JPanel panelRead = new JPanel();
        panelRead.setLayout(null);
        panelRead.setBounds(11, 243, 518, 154);
        panelRead.setBorder(BorderFactory.createTitledBorder("Read byte by Length"));

        // 添加地址标签和文本框
        JLabel label1 = new JLabel("Address：");
        label1.setBounds(9, 30, 70, 17);
        panelRead.add(label1);

        JTextField textField1 = new JTextField();
        textField1.setBounds(83, 27, 82, 23);
        textField1.setText(defaultAddress);
        panelRead.add(textField1);

        // 添加长度标签和文本框
        JLabel label2 = new JLabel("Length：");
        label2.setBounds(185, 30, 60, 17);
        panelRead.add(label2);

        JTextField textField2 = new JTextField();
        textField2.setBounds(234, 27, 102, 23);
        textField2.setText("10");
        panelRead.add(textField2);

        // 添加结果标签和文本框
        JLabel label3 = new JLabel("Result：");
        label3.setBounds(9, 58, 70, 17);
        panelRead.add(label3);

        JTextArea textArea1 = new JTextArea();
        textArea1.setLineWrap(true);
        JScrollPane jsp = new JScrollPane(textArea1);
        jsp.setBounds(83, 56, 425, 78);
        panelRead.add(jsp);

        // 添加读取按钮
        JButton button2 = new JButton("Read");
        button2.setFocusPainted(false);
        button2.setBounds(426, 24, 82, 28);
        button2.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if (button2.isEnabled() == false) return;
                super.mouseClicked(e);
                // 逐个字节读取数据
                OperateResultExOne<byte[]> read = melsecMcNet.Read(textField1.getText(), Short.parseShort(textField2.getText()));
                if (read.IsSuccess) {
                    textArea1.setText(SoftBasic.ByteToHexString(read.Content));
                } else {
                    JOptionPane.showMessageDialog(
                            null,
                            "Read Failed:" + read.ToMessageShowString(),
                            "Result",
                            JOptionPane.ERROR_MESSAGE);
                }
            }
        });
        panelRead.add(button2);

        panel.add(panelRead);
    }

    // 批量读取
    public void AddReadAll(JPanel panel) {
        JPanel panelRead = new JPanel();
        panelRead.setLayout(null);
        panelRead.setBounds(546, 243, 419, 277);
        panelRead.setBorder(BorderFactory.createTitledBorder("Read all by Length"));

        // 添加地址标签和文本框
        JLabel label1 = new JLabel("Address：");
        label1.setBounds(9, 30, 70, 17);
        panelRead.add(label1);

        JTextField textField1 = new JTextField();
        textField1.setBounds(83, 27, 82, 23);
        textField1.setText(defaultAddress);
        panelRead.add(textField1);

        // 添加长度标签和文本框
        JLabel label2 = new JLabel("Length：");
        label2.setBounds(185, 30, 60, 17);
        panelRead.add(label2);

        JTextField textField2 = new JTextField();
        textField2.setBounds(234, 27, 102, 23);
        textField2.setText("10");
        panelRead.add(textField2);

        // 添加结果标签和文本框
        JLabel label3 = new JLabel("Result：");
        label3.setBounds(9, 88, 70, 17);
        panelRead.add(label3);

        JTextArea textArea1 = new JTextArea();
        textArea1.setLineWrap(true);
        JScrollPane jsp = new JScrollPane(textArea1);
        jsp.setBounds(9, 108, 400, 150);
        panelRead.add(jsp);

        // 添加读取按钮
        JButton button2 = new JButton("Read");
        button2.setFocusPainted(false);
        button2.setBounds(426, 24, 82, 28);

        JButton readButton = new JButton("Read Data");
        readButton.setFocusPainted(false);
        readButton.setBounds(83, 58, 100, 28);
        JButton stopButton = new JButton("Stop Reading");
        stopButton.setFocusPainted(false);
        stopButton.setBounds(234, 58, 120, 28);

        readButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                startReading();
            }
        });

        stopButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                stopReading();
            }
        });
       /* button2.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if (button2.isEnabled() == false) return;
                super.mouseClicked(e);
                // 逐个字节读取数据
                OperateResultExOne<byte[]> read = melsecMcNet.Read(textField1.getText(), Short.parseShort(textField2.getText()));
                if (read.IsSuccess) {
                    textArea1.setText(SoftBasic.ByteToHexString(read.Content));
                } else {
                    JOptionPane.showMessageDialog(
                            null,
                            "Read Failed:" + read.ToMessageShowString(),
                            "Result",
                            JOptionPane.ERROR_MESSAGE);
                }
            }
        });*/
        panelRead.add(button2);
        panelRead.add(readButton);
        panelRead.add(stopButton);


        panel.add(panelRead);
    }

    /**
     * 开始读取PLC的D寄存器数据
     */
    private void startReading() {
        if (!isReading) {
            isReading = true;
            new Thread(new Runnable() {
                @Override
                public void run() {
                    while (isReading) {
                        readAndPrintData();
                        try {
                            Thread.sleep(1000); // 读取间隔，可以根据需要调整
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }).start();
        }
    }

    /**
     * 停止读取PLC的D寄存器数据
     */
    private void stopReading() {
        isReading = false;

        textArea.append("停止读取\n");
    }


    /**
     * 读取并打印PLC的D寄存器数据
     */
    private void readAndPrintData() {

        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                textArea.append(dateFormat.format(new Date()) + "第 " + (++readCount) + " 次读取\n");
                long startTime = System.currentTimeMillis();
                //    读取并打印数据的逻辑提取为一个方法
                readAndPrintSingleData("D1");
                readAndPrintSingleData("D31");
                readAndPrintSingleData("D61");
                readAndPrintSingleData("D91");
                readAndPrintSingleData("D121");
                readAndPrintSingleData("D151");
                readAndPrintSingleData("D181");
                readAndPrintSingleData("D211");
                long endTime = System.currentTimeMillis();
                textArea.append(dateFormat.format(new Date()) + "本次读取耗时: " + (endTime - startTime) + " ms\n");
                textArea.append("\n");
            }
        });

    }

    /**
     * 读取并打印寄存器数据
     *
     * @param address
     */
    private void readAndPrintSingleData(String address) {
        // 读取D寄存器的数据
        OperateResultExOne<int[]> readResult7 = melsecMcNet.ReadInt32(address, (short) 30);
        // 打印读取结果
        if (readResult7.IsSuccess) {
            printIntArray(readResult7.Content);
        } else {
            textArea.append("读取失败\n");
        }
    }

    /**
     * 打印int数组的值
     *
     * @param data int数组
     */
    private void printIntArray(int[] data) {
        for (int value : data) {
            textArea.append(value + " ");
        }
        textArea.append("\n");
    }

    // 添加报文读取测试的UI元素
    public void AddCoreRead(JPanel panel) {
        JPanel panelRead = new JPanel();
        panelRead.setLayout(null);
        panelRead.setBounds(11, 403, 518, 118);
        panelRead.setBorder(BorderFactory.createTitledBorder("报文读取测试-Full message read"));

        // 添加报文标签和文本框
        JLabel label1 = new JLabel("Message：");
        label1.setBounds(9, 30, 70, 17);
        panelRead.add(label1);

        JTextField textField1 = new JTextField();
        textField1.setBounds(83, 27, 337, 23);
        textField1.setText(SoftBasic.ByteToHexString(SiemensS7Net.BuildReadCommand(defaultAddress, (short) 1).Content, ' '));
        panelRead.add(textField1);

        // 添加结果标签和文本框
        JLabel label3 = new JLabel("Result：");
        label3.setBounds(9, 58, 70, 17);
        panelRead.add(label3);

        JTextArea textArea1 = new JTextArea();
        textArea1.setLineWrap(true);
        JScrollPane jsp = new JScrollPane(textArea1);
        jsp.setBounds(83, 56, 425, 52);
        panelRead.add(jsp);

        // 添加读取按钮
        JButton button2 = new JButton("Read");
        button2.setFocusPainted(false);
        button2.setBounds(426, 24, 82, 28);
        button2.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if (button2.isEnabled() == false) return;
                super.mouseClicked(e);
                // 读取报文数据
                OperateResultExOne<byte[]> read = melsecMcNet.ReadFromCoreServer(SoftBasic.HexStringToBytes(textField1.getText()));
                if (read.IsSuccess) {
                    textArea1.setText(SoftBasic.ByteToHexString(read.Content));
                } else {
                    JOptionPane.showMessageDialog(
                            null,
                            "Read Failed:" + read.ToMessageShowString(),
                            "Result",
                            JOptionPane.ERROR_MESSAGE);
                }
            }
        });
        panelRead.add(button2);

        panel.add(panelRead);
    }

}
